11. Exercise: Operator Overload

Exercise: Operator Overload

Thus far, you've experimented with two types of polymorphism in C++: run time and compile time polymorphism.

You've already seen how compile time polymorphism is achieved with function overloading. In this exercise you'll see how to achieve polymorphism with operator overloading as well. In fact, you can choose any operator from the ASCII table and give it your own set of rules!

Operator overloading can be useful for many things. Consider the + operator. We can use it to add ints, doubles, floats, or even std::strings.

In order to overload an operator, use the operator keyword in the function signature:

Complex operator+(const Complex& addend) {
  //...logic to add complex numbers
}

Imagine vector addition. You might want to perform vector addition on a pair of points to add their x and y components. The compiler won't recognize this type of operation on its own, because this data is user defined. However, you can overload the + operator so it performs the action that you want to implement.

Instructions

  1. Define class Point.
  2. Declare a prototype of overload method for + operator.
  3. Confirm the tests pass.

Workspace

This section contains either a workspace (it can be a Jupyter Notebook workspace or an online code editor work space, etc.) and it cannot be automatically downloaded to be generated here. Please access the classroom with your account and manually download the workspace to your local machine. Note that for some courses, Udacity upload the workspace files onto https://github.com/udacity, so you may be able to download them there.

Workspace Information:

  • Default file path:
  • Workspace type: jupyter
  • Opened files (when workspace is loaded): n/a